package com.zenithmind.gateway.event;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

/**
 * 默认网关事件发布器实现
 * 专门负责发布网关相关的事件
 * 遵循单一职责原则：只负责事件的发布逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DefaultGatewayEventPublisher implements GatewayEventPublisher {
    
    private final ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void publishEvent(GatewayEvent event) {
        try {
            log.trace("发布网关事件: {} - {}", event.getEventType(), event.getEventId());
            applicationEventPublisher.publishEvent(event);
        } catch (Exception e) {
            log.error("发布网关事件失败: {}", event.getEventType(), e);
        }
    }

    @Override
    public void publishRequestStartEvent(String requestId, String path, String method, String userId) {
        GatewayEvent.RequestStartEvent event = new GatewayEvent.RequestStartEvent(requestId, path, method, userId);
        publishEvent(event);
    }

    @Override
    public void publishRequestCompleteEvent(String requestId, int statusCode, long executionTime) {
        GatewayEvent.RequestCompleteEvent event = new GatewayEvent.RequestCompleteEvent(requestId, statusCode, executionTime);
        publishEvent(event);
    }

    @Override
    public void publishRequestErrorEvent(String requestId, String error, long executionTime) {
        GatewayEvent.RequestErrorEvent event = new GatewayEvent.RequestErrorEvent(requestId, error, executionTime);
        publishEvent(event);
    }
}
